﻿using Eneta.Portal.Common;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace Eneta.Portal.Business
{
    public class BusinessProvisioningEngine : SPWebProvisioningProvider
    {
        public override void Provision(SPWebProvisioningProperties props)
        {
            var web = props.Web;
            var lang = web.Language;
            
            web.ApplyWebTemplate("Business#0");
            EnsureContentTypes(web, PublishingWeb.GetPagesListName(web));
            web.Webs.Add("firmad", "Firmad", "Eneta portaali Firmade sait", lang, "Business#2", false, false);
            web.Webs.Add("tookuulutused", "Töökuulutused", "Eneta portaali töökuulutuste sait", lang, "Business#3",false, false);
            web.Update();
            /*
            SPSecurity.RunWithElevatedPrivileges(
                delegate()
                    {
                        SiteProvisioning.EnsureContentTypes(web, "firmad", "Firma", PublishingWeb.GetPagesListName(web.Webs["firmad"]));
                    });
            */
        }

        private static void EnsureContentTypes(SPWeb site, string pagesListName)
        {
            var pageCTs = site.Lists[pagesListName].ContentTypes;
            foreach (SPContentType contentType in site.Site.RootWeb.AvailableContentTypes)
            {
                if (IsCustomContentType(contentType) && pageCTs[contentType.Name] == null)
                    pageCTs.Add(contentType);
            }
        }

        ///<summary> 
        /// Determines whether a given content type is a custom type for this Feature.
        ///</summary> 
        private static bool IsCustomContentType(SPContentType contentType)
        {
            if (contentType.Hidden) return false;
            if (contentType.Group.ToUpper() != "Eneta") return false;
            return true;
        }
    }
}
